package com.sitech.ibnms.c3p.task.listeners.impl;

import com.sitech.ibnms.c3p.command.IOParamType;
import com.sitech.ibnms.c3p.domain.C3pTask;
import com.sitech.ibnms.c3p.domain.C3pTaskNodeIo;
import com.sitech.ibnms.c3p.mappers.C3pTaskNodeIOMapper;
import com.sitech.ibnms.c3p.task.listeners.TaskStartListener;
import com.sitech.ismp.workflow.domain.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.sitech.ibnms.c3p.util.C3pConstants.CONTEXT_ROOT_SERIAL_NO;

/**
 * 任务初始化参数存储
 * 存到数据库中  任务执行 过程中 输入输出 记录到C3P_TASK_NODE_IO表
 * 任务执行完 将
 * Created by leo on 15/8/24.
 */
@Component
public class C3pTaskContextParamsRepository implements TaskStartListener {
    @Autowired
    C3pTaskNodeIOMapper ioMapper;

    @Override
    public void onStart(C3pTask c3pTask, ProcessInstance processInstance, Map<String, String> contextParams) throws Exception {
        C3pTaskNodeIo baseIo = new C3pTaskNodeIo();
        baseIo.setC3pTaskId(c3pTask.getTaskId());
        baseIo.setProcessId(processInstance.getProcessId());
        baseIo.setSerialNo(processInstance.getSerialNo());
        baseIo.setParamType(IOParamType.CONTEXT.name());
        List<C3pTaskNodeIo> params = new ArrayList<C3pTaskNodeIo>(contextParams.size() + 1);
        for (Map.Entry<String, String> entry : contextParams.entrySet()) {
            params.add(newParam(entry.getKey(), entry.getValue(), baseIo));
        }
        params.add(newParam(CONTEXT_ROOT_SERIAL_NO, String.valueOf(getRootSerialNo(processInstance)), baseIo));
        ioMapper.insertParam(params);
    }

    private C3pTaskNodeIo newParam(String paramName, String paramValue, C3pTaskNodeIo baseObject) {
        C3pTaskNodeIo nodeIo = new C3pTaskNodeIo();
        nodeIo.setC3pTaskId(baseObject.getC3pTaskId());
        nodeIo.setProcessId(baseObject.getProcessId());
        nodeIo.setSerialNo(baseObject.getSerialNo());
        nodeIo.setParamType(baseObject.getParamType());
        nodeIo.setParamName(paramName);
        nodeIo.setParamValue(paramValue);
        return nodeIo;
    }

    private int getRootSerialNo(ProcessInstance processInstance) {
        int parentSerialNo = processInstance.getParentSerialNo();
        if (parentSerialNo == 0) {
            return processInstance.getSerialNo();
        } else {
            return ioMapper.queryRootSerialNo(parentSerialNo);
        }
    }
}
